package com.xxx.yuedong.community.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xxx.yuedong.common.R;
import com.xxx.yuedong.common.consts.ActionConstants;
import com.xxx.yuedong.common.exception.YuedongException;
import com.xxx.yuedong.community.controller.form.CommentAddNewForm;
import com.xxx.yuedong.community.controller.form.CommentDetailForm;
import com.xxx.yuedong.community.pojo.Comment;
import com.xxx.yuedong.community.service.CommentService;
import com.xxx.yuedong.utils.EventMsgSendUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/comment")
@Api(tags = "评论相关接口")
@Slf4j
@Validated
public class CommentController {
    @Autowired
    private CommentService commentService;

    @PostMapping("/add-new")
    @ApiOperation(value = "添加评论")
    @ApiOperationSupport(order = 100)
    @SaCheckLogin
    public R addNew(@Valid @RequestBody CommentAddNewForm form) {
        log.debug("开始处理 【发布评论】 参数{}", form.toString());

        Comment comment = JSONUtil.parse(form).toBean(Comment.class);
        comment.setUserId(StpUtil.getLoginIdAsLong());
        comment.setCreatedTime(LocalDateTime.now());
        // 检查是否为回复评论
        if (comment.getParentId() != null && comment.getParentId() != 0) {
            // 获取上一级评论的id
            Long parentId = comment.getParentId();
            // 根据parentId查询上一级评论
            CommentDetailForm parentComment = commentService.getCommentById(parentId);
            if (parentComment != null) {
                // 设置上一级评论的id为当前评论的parent_id
                comment.setParentId(parentId);
                commentService.insert(comment);

                //回复评论时向被回复的人发送消息
                EventMsgSendUtil.sendEventMsg(StpUtil.getLoginIdAsLong(), parentId, ActionConstants.COMMENTED_RESPONSE);

                return R.ok().put("comment", comment);
            } else {
                // 处理上一级评论不存在的情况
                String message = "添加评论失败，尝试添加的父级评论数据不存在！";
                log.warn(message);
                throw new YuedongException(404, message);
            }
        }
        // 第一级评论，将parent_id设置为0
        comment.setParentId(0L);
        commentService.insert(comment);

        //向发布动态的人发送消息
        EventMsgSendUtil.sendEventMsg(StpUtil.getLoginIdAsLong(), comment.getId(), ActionConstants.COMMENTED);

        return R.ok().put("comment", comment);
    }

    @PostMapping("/{id:[0-9]+}/delete")
    @ApiOperation(value = "删除评论")
    @ApiOperationSupport(order = 200)
    @SaCheckLogin
    public R delete(@PathVariable @Range(min = 1, message = "删除标签失败，请提交合法的ID值！") Long id) {
        log.debug("开始处理 【删除评论】 参数{}", id);
//        CommentDetailForm comment = commentService.getCommentById(id);
        commentService.deleteById(id);
        return R.ok();
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改评论")
    @ApiOperationSupport(order = 300)
    @SaCheckLogin
    public R update(@Valid @RequestBody Comment comment) {
        log.debug("开始处理 【修改评论】 参数{}", comment);
        comment.setUserId(StpUtil.getLoginIdAsLong());
        comment.setCreatedTime(LocalDateTime.now());
        commentService.update(comment);
        return R.ok();
    }

    @GetMapping("")
    @ApiOperation(value = "查看评论")
    @ApiOperationSupport(order = 400)
    @SaCheckLogin
    public R listByDynamicId(@RequestParam("dynamicId") Long id) {
        log.debug("开始处理 【根据动态ID查看分级评论】 参数{}", id);
        List<CommentDetailForm> comments = commentService.listByBuildTree(id);
        return R.ok().put("comments", comments);
    }

}
